package services.security;

import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ValidationAware;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class SecurityInterceptor implements Interceptor, SessionAware {

	
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		
		String[] publicActions = { "actions.general.WelcomeAction",
								   "actions.login.LoginAction" };
		
		// Verifies if action is public or not
		String action = invocation.getAction().getClass().getName();
		if (!action.equalsIgnoreCase(publicActions[0]) && !action.equalsIgnoreCase(publicActions[1])) {
			
			// Checks if user is logged
			Map<String,Object> session = invocation.getInvocationContext().getSession();
			if ( session == null || session.get("user") == null ||  session.get("user").equals("")){
				addActionError(invocation, "Tienes que estar logueado en la aplicación para acceder a esta pantalla");
				return "securityFailed";	
			}
		}
		return invocation.invoke();
	}
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
	}

	@Override
	public void init() {
		// TODO Auto-generated method stub
	}
	
	private void addActionError(ActionInvocation invocation, String message) {
		Object action = invocation.getAction();
		if(action instanceof ValidationAware) {
			((ValidationAware) action).addActionError(message);
		}
	}
	

	public void setSession(Map<String,Object> session) {
		// TODO Auto-generated method stub
	}
	  

}
